let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');

let indexRouter = require('./routes/index');
let usersRouter = require('./routes/users');
const {all} = require("express/lib/application");

let app = express();


//设置跨域访问
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); //包含本域地址
    res.header("Access-Control-Allow-Headers", "X-PINGOTHER,Content-type,X-Requested-With,Authorization,Content-Type, Authorization");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')

    // res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization') //Content-Type必须要设置，Authorization是用户登录注册时存入的token值，可根据需求来设置，还有其他的都需要用逗号隔开
    res.header('Access-Control-Allow-Credentials', true) // 这个必须要设置，否则解决跨域无效，注意true是字符串
    // res.header("Content-Type", "application/json;charset=utf-8");
    next();
})


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
// 公共文件夹  可以通过http://localhost:3000/public/images/1.jpg 访问
app.use('/public', express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

function userIsAllowed(callback) {
    // THIS FUNCTION WOULD CONTAIN YOUR LOGIC, PRESUMABLY ASYNCHRONOUS,
    // about whether or not the user is allowed to see files in the
    // protected directory; here, we'll use a default value of "false"
    callback(true);
};app.get('/public/*', function (req, res, next) {
    userIsAllowed(function (allowed) {
        if (allowed) {
            next(); // call the next handler, which in this case is express.static

        } else {
            res.end('You are not allowed!');
        }
    });
});


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

// ###########-=-=-=-=-==-==-=-=-=-=-==-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-==-=-===-=-==-=-=-=-=-=-=-##################


module.exports = app;
